package com.kim.weixinProject.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.dms.ezplatform.weixin.WeixinAccess;
import com.kim.weixinProject.util.WxUtils;

public class WeixinInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean isWeixinAccess = false;
		if(handler instanceof HandlerMethod){
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			if(method.isAnnotationPresent(WeixinAccess.class)){
				isWeixinAccess = true;
			}
		}
		if(isWeixinAccess){
			validateWeixinAccess(request, response);
			return true;
		}
		return false;
	}

	/**
	 * 针对微信企业号访问验证
	 * @param request
	 * @param response
	 */
	public void validateWeixinAccess(HttpServletRequest request, HttpServletResponse response){
		String sessionKey = (String) request.getSession().getAttribute("session_key");
		if(!StringUtils.isEmpty(sessionKey)){
			// TODO 获取session
		}

		String state = request.getParameter("state");
		String usercode = "";
		if(StringUtils.isEmpty(state) || !state.equals("weixin")){
			return;
		}
		String code = request.getParameter("code");
		if(StringUtils.isEmpty(code)){
			throw new RuntimeException("获取企业号失败");
		}
		usercode = WxUtils.OauthValid(code);
	
		// TODO
		// 1.通过usercode验证当前用户是否在系统中
		// 2.通过usercode登陆当前系统
	}
	
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
